'use strict';
const db = uniCloud.database();
const orderCollection = db.collection('xxf-orders');
const dbCmd = db.command;

const configCenter = require("uni-config-center"); // 读取配置中心配置
var wxConfig = configCenter({
	pluginId: 'wx-login'
}).requireFile('config.js');

exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('xxf-order event : ', event);
	const {
		uid,
		action
	} = event;
	if (!uid && action) {
		return {
			msg: '用户ID参数错误！',
			code: 0,
			data: null
		};
	}
	switch (action) {
		case 'putOrder':
			return putOrder(event); // 创建订单
		case 'payOrder':
			return payOrder(event); // 支付订单
		case 'checkOrderStatus':
			return checkOrderStatus(event); // 查询订单状态
		case 'updateOrderStatus':
			return updateOrderStatus(event); // 更新订单状态
		case 'cancelOrder':
			return cancelOrder(event); // 取消订单
		case 'getOrderList':
			return getOrderList(event); // 查询订单列表
		case 'getOrderDetail':
			return getOrderDetail(event); // 查询订单详情
		case 'getWaybillToken':
			return getWaybillToken(event); // 查询物流
		case 'shippingOrder':
			return shippingOrder(event); // 发货
		case 'receivedOrder':
			return receivedOrder(event); // 收货
		case 'getTabbarNum':
			return getTabbarNum(event); // tab角标
		default:
			return {
				msg: 'Invalid action！',
					code: 0,
					data: null
			};
	}
};

// 1-待支付；2-已支付；3-已发货；4-已收货；5-已失效；6-已退款；7-已取消；

async function getTabbarNum(params) {
	const {
		uid,
		role
	} = params;
	let numRes = null;
	if (role === 9) {
		numRes = await orderCollection.where({
			status: '2'
		}).count();
	} else {
		numRes = await orderCollection.where({
			status: '1',
			uid,
		}).count();
	}
	return {
		msg: 'success！',
		code: 1,
		data: numRes.total || 0
	}
}

async function receivedOrder(params) {
	const {
		order_id,
	} = params;
	if (order_id) {
		const updateRes = await orderCollection.where({
			_id: order_id
		}).update({
			status: '4',
			update_time: Date.now(),
		});
		if (updateRes.updated === 1) {
			return {
				msg: '订单已收货！',
				code: 1,
				data: true
			}
		} else {
			return {
				msg: '订单收货出错！',
				code: 0,
				data: false
			}
		}
	}
}

async function shippingOrder(params) {
	const {
		uid,
		token,
		openId,
		order_id,
		transactionId,
		waybill_name,
		waybill_num,
		waybill_pic,
	} = params;
	if (order_id) {
		const updateRes = await orderCollection.where({
			_id: order_id
		}).update({
			status: '3',
			waybill_name,
			waybill_num,
			waybill_pic,
			update_time: Date.now(),
		});
		if (updateRes.updated === 1) {
			// 发货成功后，上传订单
			await uniCloud.callFunction({
				name: 'xxf-wechat',
				data: {
					action: "uploadShoppingInfoToWx",
					uid,
					token,
					payer: {
						openid: openId,
					},
					order_key: {
						order_number_type: 2,
						transaction_id: transactionId,
					},
					shipping_list: [{
						tracking_no: waybill_num,
						express_company: waybill_name,
						item_desc: "硒乡坊",
					}],
				}
			});
			return {
				msg: '订单已发货！',
				code: 1,
				data: true
			}
		} else {
			return {
				msg: '订单发货出错！',
				code: 0,
				data: false
			}
		}
	}
}

async function getWaybillToken(params) {
	console.log("getWaybillToken: ", params);
	const {
		open_id,
		order_id,
		receiver_phone,
		waybill_num,
		goods_info,
		trans_id
	} = params;
	const accessTokenRes = await uniCloud.httpclient.request(
		`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wxConfig.appId}&secret=${ wxConfig.secret}`, {
			method: 'GET',
			dataType: 'json'
		});
	console.log("accessTokenRes: ", accessTokenRes);
	if (accessTokenRes.status === 200) {
		const waybillTokenRes = await uniCloud.httpclient.request(
			`https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/trace_waybill?access_token=${accessTokenRes.data.access_token}`, {
				method: 'POST',
				data: {
					openid: open_id,
					receiver_phone,
					waybill_num,
					goods_info,
					trans_id,
				},
				dataType: 'json'
			})
		console.log("waybillTokenRes: ", waybillTokenRes);
		if (waybillTokenRes.status === 200) {
			const updateRes = await orderCollection.where({
				_id: order_id
			}).update({
				waybill_token: waybillTokenRes.data.waybill_token,
				update_time: Date.now(),
			});
			console.log("waybillToken updateRes: ", updateRes);
			return {
				msg: 'success！',
				code: 1,
				data: {
					waybill_token: waybillTokenRes.data.waybill_token
				}
			}
		} else {
			return {
				msg: '请求waybill_token失败！',
				code: 0,
				data: null
			}
		}
	} else {
		return {
			msg: '请求access_token失败！',
			code: 0,
			data: null
		}
	}
}

async function getOrderDetail(params) {
	console.log('getOrderDetail: ', params);
	const {
		uid,
		id
	} = params;
	const detailRes = await orderCollection.where({
		uid,
		_id: id
	}).get();
	console.log('detailRes: ', detailRes);
	if (detailRes.data && detailRes.data.length > 0) {
		return {
			msg: '',
			code: 1,
			data: detailRes.data[0],
		};
	} else {
		return {
			msg: '暂无数据！',
			code: 0,
			data: null
		};
	}
}

async function getOrderList(params) {
	console.log('getOrderList: ', params);
	const {
		uid,
		status
	} = params;
	let listRes = {};
	if (status === '0') {
		listRes = await orderCollection.orderBy('create_time', 'desc').where({
			uid
		}).get();
	} else {
		listRes = await orderCollection.orderBy('create_time', 'desc').where({
			status,
			uid
		}).get();
	}
	console.log('listRes: ', listRes);
	if (listRes.data && listRes.data.length > 0) {
		return {
			msg: '',
			code: 1,
			data: {
				list: listRes.data,
			}
		};
	} else {
		return {
			msg: '暂无数据！',
			code: 0,
			data: {
				list: []
			}
		};
	}
}

async function cancelOrder(params) {
	console.log("cancelOrder: ", params);
	const {
		uid,
		orderId,
	} = params;
	if (orderId) {
		let orderRes = await orderCollection.where({
			_id: orderId
		}).get();
		console.log("orderRes: ", orderRes);
		if (orderRes && orderRes.data && orderRes.data.length) {
			const orderItem = orderRes.data[0];
			if (orderItem.status === '1') {
				// todo::事务
				// 取消订单的影响业务（销量还原，是否需要退款）
				// 查询确认下订单状态
				let checkRes = await checkOrderStatus(params);
				if (checkRes.result && checkRes.result.data) {
					console.log("'订单已支付！ ");
					orderRes = await orderCollection.where({
						_id: orderId
					}).get();
					console.log("orderRes after1: ", orderRes);
				}
			}
			if (orderItem.status === '2') {
				// 需要退款
				if (orderItem.notify_info) {
					const transactionId = orderItem.notify_info.transactionId || "";
					const outTradeNo = orderItem.notify_info.outTradeNo || "";
					const refundRes = await uniCloud.callFunction({
						name: 'xxf-uniPay',
						data: {
							action: "orderRefund",
							transactionId,
							outTradeNo,
							outRefundNo: orderItem._id, // 商户退款单号
							totalFee: orderItem.pay_money, // 订单总金额
							refundFee: orderItem.pay_money,
							refundDesc: "取消订单退款"
						}
					});
					console.log("refundRes: ", refundRes);
					if (refundRes.result && refundRes.result.code === 1) {
						// 订单已支付
						console.log("已支付: ");
						const updateRes = await orderCollection.where({
							_id: orderId
						}).update({
							status: '2',
							refund_info: refundRes.result.data,
							refund_time: Date.now(),
							refund_money: refundRes.result.data.refundFee,
							update_time: Date.now(),
						});
						console.log("updateRes: ", updateRes);
					} else {
						return {
							msg: '订单信息有误，无法操作，请联系客服！',
							code: 0,
							data: null
						}
					}
				}
			}
			// 取消订单
			if (orderItem.status === '1' || orderItem.status === '2') {
				// 销量恢复
				for (let i = 0; i < orderItem.product_list.length; i++) {
					const proItem = orderItem.product_list[i];
					const salesRes = await uniCloud.callFunction({
						name: 'xxf-product',
						data: {
							action: "updateProductSales",
							uid,
							id: proItem.productId,
							mode: -1
						}
					});
					console.log("salesRes: ", salesRes);
				}
				// 取消
				const newStatus = ['', '7', '6'][orderItem.status];
				const updateRes = await orderCollection.where({
					_id: orderId
				}).update({
					status: newStatus,
					update_time: Date.now(),
					invalid_time: null,
				});
				console.log("updateRes: ", updateRes);
				if (updateRes.updated === 1) {
					// 取消后的订单信息
					orderRes = await orderCollection.where({
						_id: orderId
					}).get();
					console.log("orderRes after2: ", orderRes);
					const orderObj = orderRes.data[0];
					return {
						msg: '',
						code: 1,
						data: {
							...orderObj
						}
					}
				} else {
					return {
						msg: '订单取消失败！',
						code: 0,
						data: updateRes
					}
				}
			} else {
				return {
					msg: '订单不支持取消！',
					code: 0,
					data: null
				}
			}
		} else {
			// 不存在
			return {
				msg: '订单不存在！',
				code: 0,
				data: null
			}
		}
	} else {
		// 不存在
		return {
			msg: '订单ID不存在！',
			code: 0,
			data: null
		}
	}
}

async function updateOrderStatus(params) {
	console.log("updateOrderStatus: ", params);
	const {
		orderId,
		status,
	} = params;
	if (orderId) {
		let updateParams = {
			status,
			update_time: Date.now(),
		};
		if (status === '2') updateParams.notify_info = params.notifyInfo || {};
		const updateRes = await orderCollection.where({
			orderId
		}).update({
			...updateParams
		});
		console.log("updateRes: ", updateRes);
		if (updateRes.updated === 1) {
			const whereRes = await orderCollection.where({
				orderId
			}).get();
			console.log("whereRes: ", whereRes);
			const orderObj = whereRes.data[0];
			return {
				msg: '',
				code: 1,
				data: {
					...orderObj
				}
			}
		}
	} else {
		// 不存在
		return {
			msg: '订单ID不存在！',
			code: 0,
			data: null
		}
	}
}

async function checkOrderStatus(params) {
	console.log("checkOrderStatus: ", params);
	const {
		uid,
		openId,
		orderId,
	} = params;
	let orderRes = await orderCollection.where({
		_id: orderId
	}).get();
	console.log("orderRes: ", orderRes);
	if (orderRes && orderRes.data && orderRes.data.length) {
		const orderItem = orderRes.data[0];
		let queryRes = null;
		try {
			if (orderItem.notify_info && orderItem.notify_info.transactionId) {
				queryRes = await uniCloud.callFunction({
					name: 'xxf-uniPay',
					data: {
						action: "orderQuery",
						transactionId: orderItem.notify_info.transactionId,
					}
				});
			} else {
				queryRes = await uniCloud.callFunction({
					name: 'xxf-uniPay',
					data: {
						action: "orderQuery",
						outTradeNo: orderItem._id,
					}
				});
			}
			console.log("payOrder queryRes: ", queryRes);
		} catch (err) {
			console.log("payOrder queryErr: ", err);
			queryRes = {};
		}
		if (queryRes.result && queryRes.result.code === 1) {
			// 订单已支付
			console.log("已支付: ");
			const updateRes = await orderCollection.where({
				_id: orderId
			}).update({
				status: '2',
				notify_info: queryRes.result.data,
				invalid_time: null,
				pay_time: Date.now(),
				pay_money: queryRes.result.data.totalFee,
				update_time: Date.now(),
			});
			console.log("updateRes: ", updateRes);
			if (updateRes.updated === 1) {
				return {
					msg: '订单已支付！',
					code: 1,
					data: true
				}
			}
		}
		return {
			msg: '订单未支付！',
			code: 1,
			data: false
		}
	}
	return {
		msg: '订单不存在！',
		code: 1,
		data: false
	}
}

async function payOrder(params) {
	console.log("payOrder: ", params);
	const {
		uid,
		openId,
		orderId,
	} = params;
	if (orderId) {
		let orderRes = await orderCollection.where({
			_id: orderId
		}).get();
		console.log("orderRes: ", orderRes);
		if (orderRes && orderRes.data && orderRes.data.length) {
			const orderItem = orderRes.data[0];
			if (orderItem.status === '1') {
				let checkRes = await checkOrderStatus(params);
				if (checkRes.result && checkRes.result.data) {
					return {
						msg: '订单已支付！',
						code: 1,
						data: checkRes.result.data
					}
				} else {
					// 前往支付
					console.log("前往支付: ");
					let title = "";
					if (orderItem.product_list && orderItem.product_list.length === 1) {
						title = orderItem.product_list[0].productInfo.name;
					} else {
						title = `${orderItem.product_list[0].productInfo.name}等${orderItem.totalCount}件商品`;
					}
					const unipayRes = await uniCloud.callFunction({
						name: 'xxf-uniPay',
						data: {
							action: "getOrderInfo",
							openId,
							orderNo: orderItem._id,
							money: orderItem.need_money,
							title,
						}
					});
					console.log('unipayRes:', unipayRes);
					return unipayRes.result;
				}
			} else {
				return {
					msg: '订单有误！',
					code: 0,
					data: null
				}
			}
		} else {
			// 不存在
			return {
				msg: '订单ID不存在！',
				code: 0,
				data: null
			}
		}
	}
}

async function putOrder(params) {
	const {
		uid,
		totalCount,
		totalMoney,
		activeDiscount,
		vipDiscount,
		ticketDiscount,
		totalDiscount,
		needMoney,
		proList,
		receiveInfo
	} = params;
	const nowTime = Date.now();
	const addRes = await orderCollection.add({
		uid,
		create_time: nowTime,
		update_time: nowTime,
		invalid_time: new Date(new Date(nowTime).getTime() + 1 * 60 * 60 * 1000), // 日期加1H
		pay_time: 0,
		status: '1', // 1-待支付；2-已支付；3-已发货；4-已收货；5-已失效；6-已退款；
		total_count: totalCount,
		total_money: totalMoney,
		active_discount: activeDiscount,
		vip_discount: vipDiscount,
		ticket_discount: ticketDiscount,
		total_discount: totalDiscount,
		need_money: needMoney,
		receive_info: {
			name: receiveInfo.name,
			phone: receiveInfo.phone,
			region: receiveInfo.region,
			region_str: receiveInfo.regionStr,
			address: receiveInfo.address,
		},
		product_list: proList
	});
	console.log("addRes: ", addRes.id);
	if (addRes && addRes.id) {
		for (let i = 0; i < proList.length; i++) {
			// 销量增加,库存减少
			const salesRes = await uniCloud.callFunction({
				name: 'xxf-product',
				data: {
					action: "updateProductSales",
					uid,
					id: proList[i].productId,
					mode: proList[i].count || 1
				}
			});
			console.log("salesRes: ", salesRes);
		}
		const whereRes = await orderCollection.where({
			uid,
			_id: addRes.id,
		}).get();
		console.log("whereRes: ", whereRes);
		if (whereRes && whereRes.data && whereRes.data.length) {
			const orderObj = whereRes.data[0];
			return {
				msg: '',
				code: 1,
				data: {
					...orderObj
				}
			}
		}
	} else {
		return {
			msg: '下单出错！',
			code: 0,
			data: null
		}
	}
}